package cn.woblog.android.downloader.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import java.util.List;

import cn.woblog.android.downloader.DownloadManager;

public class DownloadService extends Service {
	private static final String TAG = "DownloadService";

	public static DownloadManager DOWNLOAD_MANAGER;

	public static DownloadManager getDownloadManager(Context context) {
		if (!isServiceRunning(context)) {
			Intent downloadSvr = new Intent(context, DownloadService.class);
			context.startService(downloadSvr);
		}
		if (DownloadService.DOWNLOAD_MANAGER == null) {
			DownloadService.DOWNLOAD_MANAGER = new DownloadManager(context);
		}
		return DOWNLOAD_MANAGER;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public static boolean isServiceRunning(Context context) {
		boolean isRunning = false;

		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(Integer.MAX_VALUE);

		if (serviceList == null || serviceList.size() == 0) {
			return false;
		}

		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(
					DownloadService.class.getName())) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	@Override
	public void onDestroy() {
		if (DOWNLOAD_MANAGER != null) {
			DOWNLOAD_MANAGER.onDestory();
		}
		super.onDestroy();
	}
}
